package com.jack006.search.controller;

import com.jack006.grace.result.GraceJSONResult;
import com.jack006.search.pojo.Stu;
import org.elasticsearch.action.index.IndexRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname HelloController
 * @Description 接口实现类
 * @Date 2021-06-10 08:15
 * @Created by jack
 */
@RestController
public class HelloController {

    final static Logger logger = LoggerFactory.getLogger(HelloController.class);

    @Autowired
    private ElasticsearchTemplate esTemplate;


    @GetMapping("/hello")
    public Object hello(){
        return GraceJSONResult.ok("hello jack to files");
    }


    @GetMapping("createIndex")
    public Object createIndex(){
        esTemplate.createIndex(Stu.class);
        return GraceJSONResult.ok();
    }

    @GetMapping("deleteIndex")
    public Object deleteIndex(){
        esTemplate.deleteIndex(Stu.class);
        return GraceJSONResult.ok();
    }

    @GetMapping("addDoc")
    public Object addDoc(){

        Stu stu = new Stu();
        stu.setStuId(1001l);
        stu.setAge(18);
        stu.setName("jack");
        stu.setMoney(200.8f);
        stu.setDesc("追梦的人");
        IndexQuery query = new IndexQueryBuilder()
                .withObject(stu)
                .build();
        esTemplate.index(query);
        return GraceJSONResult.ok();
    }


    @GetMapping("updateDoc")
    public Object updateDoc(){

        Map<String,Object> updateMap = new HashMap<>();
        updateMap.put("desc","hello world");
        updateMap.put("age",16);

        IndexRequest request = new IndexRequest();
        request.source(updateMap);

        UpdateQuery uq = new UpdateQueryBuilder()
                .withClass(Stu.class)
                .withId("1001")
                .withIndexRequest(request)
                .build();

        esTemplate.update(uq);
        return GraceJSONResult.ok();
    }

    @GetMapping("getDoc")
    public Object getDoc(String id) {
        GetQuery getQuery = new GetQuery();
        getQuery.setId(id);
        Stu stu = esTemplate.queryForObject(getQuery,Stu.class);
        return GraceJSONResult.ok(stu);
    }


    @GetMapping("deleteDoc")
    public Object deleteDoc(String id) {
        esTemplate.delete(Stu.class,id);
        return GraceJSONResult.ok();
    }
}
